package com.zbw.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public void start() {
        try {
            String clientId = Config.uuidAsClientID();
            MqttClient client = new MqttClient(Config.HOST, clientId, new MemoryPersistence());
            client.setCallback(new Callback());

            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(Config.USERNAME);
            options.setPassword(Config.PASSWORD.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(50);

            MqttTopic topic = client.getTopic(Config.TOPIC);
            options.setWill(topic, "close".getBytes(), 2, true);

            client.connect(options);

            int[] Qos = {1};
            String[] topics = {Config.TOPIC};
            client.subscribe(topics, Qos);

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
        System.out.println("client subscribe is running ... ");
    }
}
